import auth from "@/utils/auth.js";
import utils from "@/utils/utils";


export default {
  async pay(resp) {
    // #ifdef  MP-WEIXIN	
    return await wxPay(resp)
    // #endif

    // #ifdef H5
    return await H5Pay(resp)
    // #endif

    // #ifdef  APP-PLUS
    return await this.appPay()
    // #endif
  },
}

//微信小程序支付
function wxPay(resp) {
  return new Promise((resolve, reject) => {
    uni.requestPayment({
      provider: 'wxpay',
      timeStamp: resp.timeStamp,
      nonceStr: resp.nonceStr,
      package: resp.package,
      signType: resp.signType,
      paySign: resp.paySign,
      success: (res) => {
        resolve(true)
      },
      fail: (err) => {
        reject(err)
      },
      complete: () => {
        utils.toLink(`/packagePages/order/list`, "redirectTo");
      }
    })
  })
}

//H5支付
async function H5Pay(resp) {
  return new Promise((resolve, reject) => {
    jWeixin.config({
      debug: resp.debug,
      appId: resp.appId,
      timestamp: resp.timestamp,
      nonceStr: resp.nonceStr,
      signature: resp.signature,
      jsApiList: ['chooseWXPay']
    })
    jWeixin.ready(() => {
      jWeixin.chooseWXPay({
        timestamp: resp.timeStamp,
        nonceStr: resp.nonceStr, // 支付签名随机串，不长于 32 位
        package: resp.package, // 统一支付接口返回的prepay_id参数值，提交格式如：prepay_id=\*\*\*）
        signType: resp.signType, // 微信支付V3的传入 RSA ,微信支付V2的传入格式与V2统一下单的签名格式保持一致
        paySign: resp.paySign, // 支付签名
        success: (res) => {
          console.log('支付成功', res)
          resolve(true)
        },
        fail: (res) => {
          console.log('支付失败', res)
          resolve(false)
        }
      });
    })
  })
}

//app支付
async function appPay() {
  let paymentMethods = await getProvider('payment')
  console.log("本机支持的支付方式", paymentMethods)

  //系统允许的支付方式
  let resp = await self.$https.post("/api/payByType/queryPayType")
  console.log("系统允许的支付方式", resp)

  if (resp.payType == 1) { //只有支付宝
    payZfb(paymentMethods, postUrl, params, self)
  } else if (resp.payType == 2) { //只有微信
    payWx(paymentMethods, postUrl, params, self)
  } else {  //微信+支付宝
    uni.showActionSheet({
      itemList: ['支付宝', '微信'],
      success: (res) => {
        console.log('选中了第' + (res.tapIndex + 1) + '个按钮');
        if (res.tapIndex == 0) {
          payZfb(paymentMethods, postUrl, params, self)
        } else {
          payWx(paymentMethods, postUrl, params, self)
        }
      },
      fail: (res) => {
        console.log(res.errMsg);
      }
    });
  }
}

//支付宝支付
async function payZfb(paymentMethods, postUrl, params, self) {
  params.payType = 'zfb'
  let result = await self.$https.post(postUrl, params)
  aliAppPay(paymentMethods, result.data)
}

//微信支付
async function payWx(paymentMethods, postUrl, params, self) {
  params.payType = 'wx'
  let result = await self.$https.post(postUrl, params)
  wxAppPay(paymentMethods, result.data)
}

function wxAppPay(paymentMethods, result) {
  if (paymentMethods.includes("wxpay")) {
    uni.requestPayment({
      provider: 'wxpay',
      orderInfo: result,
      success(res) {
        console.log('成功', res)
      },
      fail(error) {
        console.log("失败", error);
      },
    });
  } else {
    uni.$u.toast("获取微信通道失败，请检查您的微信是否正常启用")
  }
}

function aliAppPay(paymentMethods, result) {
  if (paymentMethods.includes("alipay")) {
    uni.requestPayment({
      provider: 'alipay',
      orderInfo: result,
      success(res) {
        console.log('成功', res)
      },
      fail(error) {
        console.log("失败", error);
      },
    });
  } else {
    uni.$u.toast("获取支付宝通道失败，请检查您的支付宝是否正常启用")
  }
}
